package com.maoge.main;

import com.maoge.annotation.Maoge;
import org.reflections.Reflections;
import org.reflections.scanners.MethodAnnotationsScanner;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.scanners.TypeAnnotationsScanner;
import org.reflections.scanners.TypeElementsScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Set;

/**
 * Created by bjmaozhengwei on 2018/7/4.
 */
public class Main_Reflections {


    public static void main(String[] args) {
        ConfigurationBuilder builder = new ConfigurationBuilder()
                .filterInputsBy(new FilterBuilder().includePackage("com.maoge"))
                .addUrls(ClasspathHelper.forPackage("com.maoge"))
                .setScanners(new MethodAnnotationsScanner(), new TypeAnnotationsScanner(), new TypeElementsScanner(), new SubTypesScanner());

        Reflections reflections = new Reflections(builder);
        Set<Method> methodsAnnotatedWith = reflections.getMethodsAnnotatedWith(Maoge.class);

        for (Method method : methodsAnnotatedWith) {
                //1 获取被自定义注解注释的方法 抓取自定义注解的内容和方法级别 RequestMapping注解内容
                String methodName = method.getName();
                System.out.println("methodName ---> " + methodName);
                Annotation[] methodAnnotations = method.getAnnotations();
                annotationSave(methodAnnotations);
                //2 获取拥有自定义注解方法的类 并抓取类级别 RequestMapping 注解信息
                Class<?> declaringClass = method.getDeclaringClass();
                Annotation[] classAnnotaion = declaringClass.getAnnotations();
                annotationSave(classAnnotaion);
                System.out.println("======================================");

        }
    }

    /**
     * 支持方法级别和类级别的抓取
     */
    public static void annotationSave(Annotation[] annotations){
        for (Annotation annotation : annotations) {

            if (annotation.annotationType().equals(Maoge.class)) {
                //抓取自定义注解信息
                Maoge mao = (Maoge) annotation;
                String value1 = mao.value();
                System.out.println("自定义注解值 ---> " + value1);
            }
            if (annotation.annotationType().equals(RequestMapping.class)) {
                //抓取 RequestMapping 注解内容
                RequestMapping requestMapping = (RequestMapping) annotation;
                String[] value = requestMapping.value();
                for (int i= 0; i < value.length; i++){
                    System.out.println("RequestMapping value ---> " + value[i]);
                }
            }
        }
    }
}


